from fastapi import APIRouter, Depends, Request, HTTPException
from sqlalchemy.orm import Session
from database import get_db
from models.order_models import Order

from tools.comm import get_ali_object
from datetime import datetime

router = APIRouter(prefix="/api/pay/alipay", tags=["alipay"])


@router.get("/page")
def alipay_page(order_no: str, db: Session = Depends(get_db)):
    """
    返回支付宝跳转URL（PC网页支付）
    """
    order = db.query(Order).filter(Order.order_no == order_no).first()
    if not order:
        raise HTTPException(status_code=404, detail="订单不存在")
    # 状态：0-已创建，1-已支付，2-已取消
    if order.status != 0:
        raise HTTPException(status_code=400, detail="订单状态不支持支付")

    alipay = get_ali_object()
    query_params = alipay.direct_pay(
        subject=f"订单 {order.order_no}",
        out_trade_no=order.order_no,
        total_amount=float(order.total_amount),
    )
    # 使用AliPay对象中的网关地址，而不是硬编码
    pay_url = f"{alipay.gateway}?{query_params}"
    return {"code": 0, "msg": "ok", "data": {"pay_url": pay_url}}


@router.post("/notify")
async def alipay_notify(request: Request, db: Session = Depends(get_db)):
    """
    支付宝服务器异步通知（必须返回纯文本 'success' 才视为收到）
    """
    form = await request.form()
    data = dict(form)
    sign = data.pop("sign", None)
    alipay = get_ali_object()
    ok = alipay.verify(data, sign) if sign else False
    if not ok:
        return "fail"
    out_trade_no = data.get("out_trade_no")
    trade_no = data.get("trade_no")
    order = db.query(Order).filter(Order.order_no == out_trade_no).first()
    if not order:
        return "fail"
    # 状态：0-已创建，1-已支付，2-已取消
    if order.status != 1:  # 如果订单还未支付，更新为已支付状态
        order.status = 1  # 1-已支付
        db.commit()
    return "success"
@router.get("/return")
def alipay_return(request: Request, db: Session = Depends(get_db)):
    """
    支付宝同步返回（浏览器跳转），这里简单返回状态，前端可据此跳支付结果页
    """
    params = dict(request.query_params)
    sign = params.pop("sign", None)
    alipay = get_ali_object()
    ok = alipay.verify(params, sign) if sign else False
    out_trade_no = params.get("out_trade_no")
    status = "invalid"
    if ok and out_trade_no:
        order = db.query(Order).filter(Order.order_no == out_trade_no).first()
        if order:
            status = str(order.status)
    return {"code": 0, "msg": "ok", "data": {"verified": ok, "order_no": out_trade_no, "status": status}}


